package com.heima.comment.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentLike;
import com.heima.comment.pojos.CommentVo;
import com.heima.comment.service.CommentService;
import com.heima.common.constants.HotArticleConstants;
import com.heima.feign.article.IArticleClient;
import com.heima.feign.user.IUserClient;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.comment.dtos.CommentDto;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.dtos.CommentSaveDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: Tangguo
 * @Date: 2023-06-27  13:07
 */
@Service
@Slf4j
public class CommentServiceImpl implements CommentService {

    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private IUserClient userClient;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 保存文章评论
     * @param dto :
     * @return ResponseResult
     */
    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        //1.参数校验
        if(dto==null||dto.getArticleId()==null||StringUtils.isBlank(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.必须登录后才能发表评论
        ApUser user = AppThreadLocalUtil.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        ApUser dbUser = userClient.findUserById(user.getId());
        if(dbUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN,"当前你还未登录，请登录后操作");
        }

        //2.1先判断当前文章是否开启了评论功能
        ResponseResult resultRes = articleClient.findArticleConfigByArticleId(dto.getArticleId());
        if (resultRes.getCode() == 200) {
            ApArticleConfig apArticleConfig =
                    JSON.parseObject(JSON.toJSONString(resultRes.getData()), ApArticleConfig.class);
            if (!apArticleConfig.getIsComment()) {
                //当前文章不可评论
                return ResponseResult.errorResult(AppHttpCodeEnum.ARTICLE_REFUSE_COMMENT);
            }
        }
        //3.评论内容不能超过140字
        if (dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论内容不能超过140字");
        }
        //4.评论内容需要做文本垃圾检测
        //类似文章的纯文本审核，先通过自定义敏感词审核，审核通过，再调用百度审核

        //5.保存评论
        //5.1创建
        ApComment apComment =new ApComment();
        apComment.setAuthorId(user.getId());
        apComment.setAuthorName(dbUser.getName());
        apComment.setEntryId(dto.getArticleId());
        apComment.setType((short)0);
        apComment.setContent(dto.getContent());
        apComment.setImage(dbUser.getImage());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setFlag((short)0);
        apComment.setCreatedTime(new Date());

        //5.2使用mongo数据库保存数据
        mongoTemplate.save(apComment);

        //6.发送消息，进行聚合
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setArticleId(dto.getArticleId());
        mess.setAdd(1);
        mess.setType(UpdateArticleMess.UpdateArticleType.COMMENT);

        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC,JSON.toJSONString(mess));


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询评论列表
     * 展示评论内容、评论的作者、点赞数、回复数、时间
     * @param dto :
     * @return ResponseResult
     */
    @Override
    public ResponseResult loadComment(CommentDto dto) {

        //1.参数校验
        if(dto==null||dto.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询评论列表，根据当前文章进行检索，按照创建时间倒序，分页查询（默认10条数据）
        //2.1创建mongo分页查询条件
        Query query=Query.query(Criteria.where("entryId").is(dto.getArticleId()).and("createdTime").lt(dto.getMinDate()));
        query.with(Sort.by(Sort.Direction.DESC,"createdTime")).limit(10);
        List<ApComment> apCommentsList = mongoTemplate.find(query, ApComment.class);
        //3.在结果返回中，如果当天登录人点赞了某条评论，需要高亮展示“**点赞按钮**”
        //3.1用户未登录
        ApUser user = AppThreadLocalUtil.getUser();
        ApUser dbUser = userClient.findUserById(user.getId());
        if (dbUser == null) {
            return ResponseResult.okResult(apCommentsList);
        }
        //3.2用户登录,需要高亮展示点赞按钮
        List<String> idList = apCommentsList.stream().map(apComment -> apComment.getId()).collect(Collectors.toList());
        Query query1 = Query.query(Criteria.where("commentId").in(idList).and("authorId").is(user.getId()));
        List<ApCommentLike> apCommentLikes = mongoTemplate.find(query1, ApCommentLike.class);
        if (apCommentLikes == null) {
            return ResponseResult.okResult(apCommentLikes);
        }

        List<CommentVo> resultList = new ArrayList<>();
        apCommentLikes.forEach(x -> {
            CommentVo vo = new CommentVo();
            BeanUtils.copyProperties(x, vo);
            for (ApCommentLike apCommentLike : apCommentLikes) {
                if (x.getId().equals(apCommentLike.getCommentId())) {
                    vo.setOperation((short) 0);
                    break;
                }
            }
            resultList.add(vo);
        });

        return ResponseResult.okResult(resultList);
    }


    /**
     * 点赞评论
     * @param dto:
     * @return ResponseResult
     */
    public ResponseResult likeComment(CommentLikeDto dto){
        //1.参数校验
        if(dto==null||dto.getCommentId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断用户是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN,"当前未登录，请登录后再操作！");
        }

        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        //3.用户点赞
        if(dto.getOperation()==0){
            ApCommentLike commentLike = mongoTemplate.findById(Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("authorId").is(user.getId())), ApCommentLike.class);
            if(commentLike==null) {
                //3.1增加点赞数
                apComment.setLikes(apComment.getLikes() + 1);
                //3.2记录当前评论数据记录
                mongoTemplate.save(apComment, "ap_comment");

                //3.3保存评论点赞数据
                ApCommentLike apCommentLike = new ApCommentLike();
                apCommentLike.setAuthorId(user.getId());
                apCommentLike.setCommentId(dto.getCommentId());
                apCommentLike.setOperation((short) 0);
                mongoTemplate.save(apCommentLike, "ap_comment_like");
            }else {
                apComment.setLikes(1);
                mongoTemplate.save(apComment, "ap_comment");
            }

        }else {
            int likes=apComment.getLikes()-1;
            if(likes<0){
                apComment.setLikes(0);
            }
            //4.取消点赞
            apComment.setLikes(apComment.getLikes()-1);
            //3.2记录当前评论数据记录
            mongoTemplate.save(apComment,"ap_comment");

            //删除评论点赞数据
            mongoTemplate.remove(Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("authorld").is(user.getId())),ApCommentLike.class);


        }
        //5.更新点赞数据
        Map<String,Object> map=new HashMap();
        map.put("likes",apComment.getLikes());
        return ResponseResult.okResult(map);
        //6.返回数据
    }




}
